#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <winsock2.h>
#include <windows.h>
#include "sqlite3.h"
#include "mongoose.h"

static sqlite3 *db;
static int64_t next_insert = 0;

// 数据库初始化
void init_db()
{
    int rc = sqlite3_open("data.db", &db);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(1);
    }

    char *sql = "CREATE TABLE IF NOT EXISTS temps("
                "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                "temp REAL NOT NULL,"
                "time DATETIME DEFAULT CURRENT_TIMESTAMP);";
    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK)
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
}

// HTTP请求处理
void fn(struct mg_connection *c, int ev, void *ev_data)
{
    if (ev == MG_EV_HTTP_MSG)
    {
        struct mg_http_message *hm = (struct mg_http_message *)ev_data;

        if (mg_match(hm->uri, mg_str("/api/data"), NULL))
        {
            sqlite3_stmt *stmt;
            char *sql = "SELECT temp, time FROM temps ORDER BY time DESC LIMIT 100;";
            char json[4096] = "[";

            if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK)
            {
                while (sqlite3_step(stmt) == SQLITE_ROW)
                {
                    char record[128];
                    snprintf(record, sizeof(record),
                             "{\"temp\":%.1f,\"time\":\"%s\"},",
                             sqlite3_column_double(stmt, 0),
                             sqlite3_column_text(stmt, 1));
                    strcat(json, record);
                }
                sqlite3_finalize(stmt);
            }

            if (json[strlen(json) - 1] == ',')
                json[strlen(json) - 1] = '\0';
            strcat(json, "]");

            mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s", json);
        }
        else
        {
            struct mg_http_serve_opts opts = {.root_dir = "."};
            mg_http_serve_dir(c, hm, &opts);
        }
    }
}

int main()
{
    printf("Program started.\n"); // 添加调试信息

    // 初始化数据库
    init_db();

    // 启动浏览器
    ShellExecute(0, "open", "http://localhost:8080/index.html", 0, 0, SW_SHOW);

    // 启动Web服务器
    struct mg_mgr mgr;
    mg_mgr_init(&mgr);
    mg_http_listen(&mgr, "http://localhost:8080", fn, NULL); // 注意第四个参数现在可用

    // 主循环
    for (;;)
    {
        mg_mgr_poll(&mgr, 100);
        // 每5秒插入数据
        int64_t now = mg_millis();
        if (now > next_insert)
        {
            double temp = 20 + (rand() % 100) / 10.0; // 模拟温度数据
            printf("Inserting data: temp = %.1f\n", temp); // 打印要存储的数据
            char sql[128];
            snprintf(sql, sizeof(sql),
                     "INSERT INTO temps(temp) VALUES(%.1f);", temp);
            sqlite3_exec(db, sql, 0, 0, 0);
            next_insert = now + 5000; // 5秒间隔
        }
    }

    sqlite3_close(db);
    printf("Waiting for user input...\n"); // 添加调试信息
    getchar(); // 等待用户输入
    return 0;
}